﻿// See https://aka.ms/new-console-template for more information
using Mbs.Utils.Sockets;
using Mbs.Utils.Sockets.Extensions;
using Mbs.Utils.ThreadPool;
using NPOI.SS.Formula.Functions;
using static System.Net.Mime.MediaTypeNames;
using System.Net.Sockets;
using System.Threading.Channels;

Console.WriteLine("Welcome To Use TCP Test Client");
string host = "127.0.0.1";//"127.0.0.1";47.96.228.64
int port = 5005;//40015;
int coreThread = 5;
int maxThread = 10;
int clientCount = 100;
string send = "";
Console.WriteLine($"请输入服务器地址[{host}]:");
var _host = Console.ReadLine();
if(! _host.IsNullOrWhiteSpace()) host=_host;
Console.WriteLine($"请输入服务器端口[{port}]:");
var _port = Console.ReadLine();
if (!_port.IsNullOrWhiteSpace()) port = int.Parse(_port.ToString());
Console.WriteLine($"请输入核心线程数[{coreThread}]");
var _coreThread = Console.ReadLine();
if (!_coreThread.IsNullOrWhiteSpace()) coreThread = int.Parse(_coreThread.ToString());
Console.WriteLine($"请输入最大线程数[{maxThread}]");
var _maxThread = Console.ReadLine();
if (!_maxThread.IsNullOrWhiteSpace()) maxThread = int.Parse(_maxThread.ToString());
Console.WriteLine($"请输入客户端数量[{clientCount}]");
var _clientCount = Console.ReadLine();
if (!_clientCount.IsNullOrWhiteSpace()) clientCount = int.Parse(_clientCount.ToString());
Console.WriteLine($"请输入连接之后要发送的数据[{send}]");
send = Console.ReadLine();

Console.Clear();
Console.WriteLine($"将要连接{host}:{port},核心线程{coreThread},最大线程{maxThread},客户端数量{clientCount}");
Console.WriteLine("按回车开始，按Ctrl + C 退出");
Console.ReadLine();

ThreadPoolExecutor poolExcutor = new(coreThread, maxThread, KeepAliveTimeout: 5000, QueueCount: 200);
WorkTask<int>[] workTasks = new WorkTask<int>[clientCount];
List<Mbs.Utils.Sockets.TcpClient> tcpClients = new List<Mbs.Utils.Sockets.TcpClient>();
for (int i = 0; i < clientCount; i++)
{

    System.Threading.Thread.Sleep(100);
    var woker = WorkTask.Factory.StartNew(t =>
    {
        int xx = int.Parse(t.ToString()!);
        //Console.WriteLine($"Task Id:{Environment.CurrentManagedThreadId},Parameter:{t}");
        //return t == null ? default(int?) : (int)t + 1;
        Console.ForegroundColor = ConsoleColor.Green;
                // Console.WriteLine($"{c.RemoteEndPoint} connected.");
        Console.WriteLine($"Thread Start.");
        Mbs.Utils.Sockets.TcpClient client = new Mbs.Utils.Sockets.TcpClient(host, port, id: xx)
        {
            //ConnectTimeout = 2000,
            //ReconnectEnable = true,
            OnConnected = (c) =>
            {
                Console.ForegroundColor = ConsoleColor.Green;
                // Console.WriteLine($"{c.RemoteEndPoint} connected.");
                Console.WriteLine($"任务编号{c.NetConnection.Id} --> {c.RemoteEndPoint} 已连接.");

            },
            OnReceived = (c) =>
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine($"任务编号{c.NetConnection.Id} --> 收到消息，来自 {c.RemoteEndPoint}:" + string.Join(" ", c.Buffers.Select(x => x.ToString("X2")).ToArray()) + "-->" + System.Text.Encoding.Default.GetString(c.Buffers));
                //Console.WriteLine($"Received from {c.RemoteEndPoint}:");
                //Console.WriteLine(string.Join(" ", c.Buffers.Select(x => x.ToString("X2")).ToArray()));
                //Console.WriteLine(System.Text.Encoding.Default.GetString(c.Buffers));
                // c.NetConnection.Send(c.Buffers);
            },
            OnDisconnected = (c) =>
            {
                Console.ForegroundColor = ConsoleColor.Red;
                //Console.WriteLine($"{c.RemoteEndPoint} disconnected.");
                Console.WriteLine($"任务编号{c.NetConnection.Id} --> {c.RemoteEndPoint} 失去连接.");
            },
            OnStarted = (c) =>
            {
                Console.ForegroundColor = ConsoleColor.Green;
                //Console.WriteLine($"{c.RemoteEndPoint} started.");
                Console.WriteLine($"任务编号{c.NetConnection.Id} --> {c.RemoteEndPoint} 就绪.");
                // if (!send.IsNullOrWhiteSpace())
                // {
                //     Console.WriteLine($"任务编号 {c.NetConnection.Id} --> 发送 {send}.");
                //     c.NetConnection.Send(send);
                // }
                int MachineId = c.NetConnection.Id;
                int TotalCycles = 0;
                int TotalPots = 0;
                int _totalPot=0;
                while(true)
                { 
                    TotalCycles += 20;
                    _totalPot += 1;
                    TotalPots = _totalPot / 8;
                    
                    var bytData = new byte[14];

                    //数据包：ID(2Bytes) 圈数(4Bytes) 锅数(4Bytes) 状态(1Byte) 事件(1Byte)
                    bytData[0] = 0x02;

                    bytData[1] = (byte)(MachineId & 0xFF);
                    bytData[2] = (byte)((MachineId & 0xFF00) >> 8);


                    bytData[3] = (byte)(TotalCycles & 0xFF);
                    bytData[4] = (byte)((TotalCycles & 0xFF00) >> 8);
                    bytData[5] = (byte)((TotalCycles & 0xFF0000) >> 16);
                    bytData[6] = (byte)((TotalCycles & 0xFF000000) >> 24);

                    bytData[7] = (byte)(TotalPots & 0xFF);
                    bytData[8] = (byte)((TotalPots & 0xFF00) >> 8);
                    bytData[9] = (byte)((TotalPots & 0xFF0000) >> 16);
                    bytData[10] = (byte)((TotalPots & 0xFF000000) >> 24);

                    //PotStatus 
                    bytData[11] = 1;


                    //PotEvent
                    bytData[12] = 1;

                    bytData[13] = 0x03;





                    c.NetConnection.Send(bytData);
                    Console.WriteLine($"任务编号 {c.NetConnection.Id} --> 发送 {System.Text.Encoding.Default.GetString(bytData)}.");

                    
                    
                    System.Threading.Thread.Sleep(1000);
                    //break;
                }

            },
            OnStopped = (c) =>
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                //Console.WriteLine($"{c.RemoteEndPoint} stopped.");
                Console.WriteLine($"任务编号{c.NetConnection.Id} --> {c.RemoteEndPoint} 已停止.");
            },
            OnException = (c) =>
            {
                Console.ForegroundColor = ConsoleColor.Red;
                //Console.WriteLine($"{c.RemoteEndPoint} exception:Message:{c.Exception.Message},StackTrace:{c.Exception.StackTrace.ToString()}.");
                Console.WriteLine($"任务编号{c.NetConnection.Id} --> {c.RemoteEndPoint} 错误:{c.Exception.Message},StackTrace:{c.Exception.StackTrace.ToString()}.");
            },
            OnClientFull= (c) =>
            {
                Console.WriteLine("#######################################################");
            },
            OnTryConnecting = (c) =>
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                //Console.WriteLine($"try connect {c.Counter} ...");
                Console.WriteLine($"任务编号{c.NetConnection.Id} --> {c.LocalEndPoint} 第 {c.Counter} 次重试....");
            }
        };
        lock (tcpClients)
        {
            tcpClients.Add(client);
        }
        // set keep alive
        client.UseKeepAlive(true, 500, 500);

        // tr connnect stratagy
        // client.UseTryConnectionStrategy(new DefaultTryConnectionStrategy());

        try
        {
            client.Start();
            Thread.Sleep(10 * 1000);
        }
        catch (Exception ex)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine($"线程编号{xx} --> Message:{ex.Message},StackTrace:{ex.StackTrace.ToString()}");
        }
        //Console.ReadLine();
        return 1;// t == null ? default(int?) : (int)t + 1;

    }, i, poolExcutor);
    workTasks[i] = woker;
}

Console.WriteLine("主线程启动等待");
WorkTask.WaitAll(workTasks);
//Console.WriteLine(workTasks.Sum(t => t.Result));
Console.ReadLine();